package com.xkcoding.mq.rabbitmq.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * 自定义序列化操作
 *
 * @author: GuoZi
 * @date: 2020/12/10 19:32
 */
@Slf4j
public class BaseDtoMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        byte[] bytes;
        bytes = JSONObject.toJSONString(o).getBytes();
        return new Message(bytes, messageProperties);
    }

    @Override
    public String fromMessage(Message message) throws MessageConversionException {
        byte[] bytes = message.getBody();
        //优先使用json序列化
        String json = new String(bytes);
        return json;
    }
}
